<?php

namespace App\Http\Middleware;

use App\Kit\RedisKey;
use App\Kit\Token;
use App\Models\AdminModel;
use App\Models\LogModel;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Redis;
use stdClass;

class Api
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @param  string|null  ...$guards
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $this->apiLog($request);
        $uri = substr($request->path(), 9);
        $noAuth = ['login', 'register', 'code/login', 'address', 'upload', 'sms'];
        if(in_array($uri, $noAuth)) {
            return $next($request);
        }

        $token = $request->header('token');
        $err = [
            'data' => [],
            'message' => '',
            'code' => 400
        ];
        if(empty($token)) {
            return response()->json($err);
        }

        $payload = Token::decodeToken($token);
        if(!$payload) {
            return response()->json($err);
        }

        $driver_id = $payload->data->id ?? '';
        if(empty($driver_id)) {
            return response()->json($err);
        }

        $storage_token = Token::get_api_token($driver_id);
        if($token != $storage_token) {
            return response()->json($err);
        }

        $auth = new stdClass;
        $auth->id = $driver_id;
        $auth->name = $payload->data->name;
        $request->attributes->add(['auth' => $auth]);
        return $next($request);
    }

    public function apiLog($request)
    {
        $params = $request->all();
        $log = new LogModel();
        $log->url = $request->url();
        $log->ip = $request->ip();
        $log->useragent = $request->server('HTTP_USER_AGENT');
        $log->content = json_encode($params);
        $log->save();
    }



}
